import type { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from "axios";
import axios from "axios";
import { message } from "antd";
import { store } from "@/store";

const http: AxiosInstance = axios.create({
    baseURL: import.meta.env.REACT_APP_API_URL,
    timeout: 5000,
});

// 请求拦截器
http.interceptors.request.use((config: InternalAxiosRequestConfig) => {
    const state = store.getState();
    const token = state.auth?.token;
    if (token) config.headers['Authorization'] = `Bearer ${token}`;

    // 开发环境下为GET请求添加时间戳防止缓存
    if (import.meta.env.DEV && config.method?.toLowerCase() === 'get') {
        config.params = config.params || {};
        config.params.t = Date.now();
    }

    return config;
});

// 响应拦截器
http.interceptors.response.use(
    (response: AxiosResponse) => {
        // 安全处理可能为空的响应数据（如304缓存响应）
        if (!response.data) {
            const errorMsg = 'API响应数据为空';
            message.error(errorMsg);
            return Promise.reject(new Error(errorMsg));
        }

        const res = response.data;
        if (res.code !== 200) {
            message.error(res.code + ":" + res.message);
            return Promise.reject(new Error(res.message));
        }
        return response.data;
    },
    (error) => {
        // 直接抛出错误，由调用方处理
        return Promise.reject(error);
    }
);

export default http;